package com.mhuang.module.wechat.service.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mhuang.common.utils.network.NetWorkUtils;
import com.mhuang.module.wechat.config.WechatConfig;
import com.mhuang.module.wechat.service.WechatConfigService;
import com.mhuang.wechat.common.config.WeConfig;

/**
 * 
 * @Description 微信配置service
 * @author mHuang
 * @date 2015年7月13日 上午11:36:52 
 * @version V1.0.0
 */
@Service("wechatConfigService")
public class WechatConfigServiceImpl implements WechatConfigService{

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private WechatConfig wechatConfig;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public Map<String, Object> queryConfig() {
		String queryConfig = "SELECT id,appId,appSecret,token,payKey,mchId from wechat_config where status = 1 and serverType = ?";
		try{
			//jdbc查询数据为null的时候会出现的异常。与目标不符合
			return jdbcTemplate.queryForMap(queryConfig,new Object[]{wechatConfig.getWechat_server_type()});
		}catch(EmptyResultDataAccessException e){
			logger.error("WECHAT CONFIG 查询数据列不对的异常（INFO）：",e);
			return null;
		}
		
	}
	
	/**
	 * 
	 * @Description 获取access_token
	 * @author mHuang
	 * @param type
	 * @param id
	 * @return
	 */
	public String queryToken(final String type,Long id){
		String queryTokenSql = null;
		
		if(StringUtils.equals(type, WechatConfig.Config.serverToken.name())){
			queryTokenSql = " SELECT serverToken from wechat_config where id = ? and unix_timestamp(now()) - unix_timestamp(tokenRefreshTime) < ? ";
		}else if(StringUtils.equals(type, WechatConfig.Config.webTicket.name())){
			queryTokenSql = " SELECT jsTicket from wechat_config where id = ? and unix_timestamp(now()) - unix_timestamp(ticketRefreshTime) < ? ";
		}else{
			return null;
		}
		try{
			//jdbc查询数据为null的时候会出现的异常。与目标不符合
			return jdbcTemplate.queryForObject(queryTokenSql,new Object[]{id,wechatConfig.getWechat_token_refreshTime()}, String.class);
		}catch(EmptyResultDataAccessException e){
			logger.error("查询数据列不对的异常（INFO）：",e);
			return null;
		}
	}
	
	public int updateToken(String type,String value,Long id){
		String updateTokenSql = null;
		
		if(StringUtils.equals(type, WechatConfig.Config.serverToken.name())){
			updateTokenSql = "update wechat_config set serverToken=? , tokenRefreshTime = now() where id = ?";
		}else if(StringUtils.equals(type, WechatConfig.Config.webTicket.name())){
			updateTokenSql = "update wechat_config set jsTicket=? , ticketRefreshTime = now() where id = ?";
		}else{
			return -1;
		}
		return jdbcTemplate.update(updateTokenSql,new Object[]{value,id});
	}
	
	/**
	 * 
	 * @Description 获取token
	 * @author mHuang
	 * @return
	 */
	public String getToken(){
		return getToken(WechatConfig.Config.serverToken.name(), WeConfig.CONFIGID);
	}
	
	public String getJSToken(){
		return getToken(WechatConfig.Config.webTicket.name(),WeConfig.CONFIGID);
	}
	
	public String getToken(String type,Long id){
		String token = (String)this.queryToken(type, id);
		if(StringUtils.isEmpty(token)){
			String tmp;
			if(StringUtils.equals(type, WechatConfig.Config.serverToken.name())){
				tmp = NetWorkUtils.sync(wechatConfig.getWechat_access_token_url());
			}else if(StringUtils.equals(type, WechatConfig.Config.webTicket.name())){
				tmp = NetWorkUtils.sync(wechatConfig.getWechat_jstoken_url().replace("ACCESS_TOKEN", getToken(WechatConfig.Config.serverToken.name(),WechatConfig.CONFIG_ID)));
			}else{
				return null;
			}
			JSONObject json = JSON.parseObject(tmp);
			if(!CollectionUtils.isEmpty(json)){
				if(json.containsKey("access_token")){
					token = json.getString("access_token");
					updateToken(WechatConfig.Config.serverToken.name(),token,WechatConfig.CONFIG_ID);
				}else if(json.containsKey("ticket")){
					token = json.getString("ticket");
					updateToken(WechatConfig.Config.webTicket.name(),token,WechatConfig.CONFIG_ID);
				}else{
					logger.info("微信返回"+type+"access_token错误:"+json);
				}
			}else{
			    logger.info("微信返回access_token错误:"+tmp);
			}
		}
		return token;
	}
}
